package com.elong.businesstravel.base.unionlogin.weixin;

import java.nio.MappedByteBuffer;
import java.util.Map;
import java.util.Set;

import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.elong.businesstravel.ELongBusinessTravelApplication;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.baseactivity.BaseActivity;
import com.elong.businesstravel.base.umeng.socialize.CustomShareDialog;
import com.elong.businesstravel.base.unionlogin.UnionLoginSucceed;
import com.elong.businesstravel.entitys.AccessToken;
import com.elong.businesstravel.entitys.UnionLoginInfo;
import com.elong.businesstravel.entitys.WeChatUserInfo;
import com.elong.businesstravel.include.Version;
import com.elong.businesstravel.protocol.ProtocolDef;
import com.elong.businesstravel.protocol.unionlogin.GetOpenIdRequest;
import com.elong.businesstravel.protocol.unionlogin.GetOpenIdResponse;
import com.elong.businesstravel.protocol.unionlogin.GetWeiXinUserInfoRequest;
import com.elong.businesstravel.protocol.unionlogin.GetWeiXinUserInfoResponse;
import com.tencent.mm.sdk.openapi.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendAuth;
import com.tencent.mm.sdk.openapi.SendAuth.Resp;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.UMSsoHandler;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMDataListener;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.SinaSsoHandler;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

/**
 * 微信联合登陆
 * 
 * @author lenovo
 * 
 */
public class WeChatUnionLogin {

	/** 获取微信openid ,根据返回的token替换%code@ */
	public static final String URL_GET_OPEN_ID = "https://api.weixin.qq.com/sns/oauth2/access_token?"
			+ "appid="
			+ CustomShareDialog.WX_APPID
			+ "&secret="
			+ CustomShareDialog.WX_APPSECRET
			+ "&code=%code@"
			+ "&grant_type=authorization_code";

	/** 获取用户信息 */
	public static final String URL_GET_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?"
			+ "access_token=%access_token@" + "&openid=%openid@";

	/** 1- 微博, 2 - QQ, 3 - 微信 */
	public static final String OPEN_TYPE = "3";

	private Context mContext;
	private ELongBusinessTravelApplication mApplication;
	private IWXAPI api;

	private AccessToken mAccessToken;
	private WeChatUserInfo mWeChatUserInfo;
	private UnionLoginSucceed mUnionLoginSucceed;
	private UnionLoginInfo mUnionLoginInfo = new UnionLoginInfo();

	public WeChatUnionLogin(Context context) {
		mContext = context;
		mApplication = (ELongBusinessTravelApplication) mContext
				.getApplicationContext();
		initWeChatUnionLogin();
	}

	private void initWeChatUnionLogin() {
		api = WXAPIFactory.createWXAPI(mContext, CustomShareDialog.WX_APPID,
				true);

	}

	public void onClickLogin() {
		if (isWeiXinShare()) {
			final SendAuth.Req req = new SendAuth.Req();
			req.scope = "snsapi_userinfo";
			req.state = "weixin";
			// req.transaction = "WeChatUnionLogin";
			req.transaction = buildTransaction("WeChatUnionLogin");
			api.sendReq(req);
		}else {
			((BaseActivity)mContext).hideWaitDialog();
		}
	}

	/**
	 * 是否可以分享微信和朋友圈
	 * 
	 * @return false不能分享，true可以分享
	 */
	private boolean isWeiXinShare() {
		if (!api.isWXAppInstalled()) {
			HandlerToastUI.getHandlerToastUI(mContext, "你还没有安装微信");
			return false;
		} else if (!api.isWXAppSupportAPI()) {
			HandlerToastUI.getHandlerToastUI(mContext, "你安装的微信版本不支持当前API");
			return false;
		}

		return true;
	}

	public void getOpenId(String code) {
		NetworkClient.getNetworkClient().GetRequest(
				new GetOpenIdRequest(mContext, code), new GetOpenIdResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						mAccessToken = accessToken;
						mUnionLoginInfo.openid = mAccessToken.openid;
						mUnionLoginInfo.opentype = OPEN_TYPE;
						getUserInfo();
					}
				});
	}

	private void getUserInfo() {
		NetworkClient.getNetworkClient().GetRequest(
				new GetWeiXinUserInfoRequest(mContext,
						mAccessToken.access_token, mAccessToken.openid),
				new GetWeiXinUserInfoResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						mWeChatUserInfo = weChatUserInfo;
						mUnionLoginInfo.screen_name = mWeChatUserInfo.nickname;
						if (null != mUnionLoginSucceed) {
							mUnionLoginSucceed
									.onUnionLoginSucceed(mUnionLoginInfo);
						}
					}
				});
	}

	public void onResp(Activity activity, BaseResp resp) {

		switch (resp.errCode) {
		case BaseResp.ErrCode.ERR_OK: {
			DebugLog.logI("BaseResp.ErrCode.ERR_OK");
			// result = R.string.errcode_success;
			if (resp instanceof SendAuth.Resp) {
				SendAuth.Resp sendResp = (Resp) resp;
				// if ("WeChatUnionLogin".equals(sendResp.transaction)) {
				if (null != sendResp.transaction
						&& sendResp.transaction.contains("WeChatUnionLogin")) {
					DebugLog.logI("token : " + sendResp.token);
					// getOpenId(sendResp.token);
					// return ;
					mApplication.mWeChatCode = sendResp.token;
				} else {

				}
			} else {
			}
			break;
		}
		case BaseResp.ErrCode.ERR_USER_CANCEL: {
			// result = R.string.errcode_cancel;
			// break;
		}
		case BaseResp.ErrCode.ERR_AUTH_DENIED: {
			// result = R.string.errcode_deny;
			// break;
		}
		default:
			// result = R.string.errcode_unknown;
			// HandlerToastUI.getHandlerToastUI(mContext, "微信授权失败");
			break;
		}

		activity.finish();

	}

	/**
	 * 联合登陆成功监听
	 * 
	 * @param unionLoginSucceed
	 */
	public void setUnionLoginSucceedListener(UnionLoginSucceed unionLoginSucceed) {
		mUnionLoginSucceed = unionLoginSucceed;
	}

	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}

}
